<template>
	<div v-if="!showLogin2" class="login-page-container">
		<global-svg-icon icon-name="login-bottom" width="100%" height="100%" style="position: absolute; z-index: 99"></global-svg-icon>
		<global-svg-icon icon-name="login-center-icon" width="100%" height="100%" style="position: absolute; z-index: 99"></global-svg-icon>

		<div class="login-page">
			<global-svg-icon icon-name="login-center" width="100%" height="100%" style="position: absolute; z-index: 99"></global-svg-icon>
			<div class="login-page-from">
				<div class="login-form-card">
					<div class="login-title">泵业分公司AI安全管控平台</div>
					<a-form ref="refForm" layout="vertical" :model="loginForm" style="margin-left: 90px">
						<div class="_title">
							<img src="../../../global-assets//imgs/diamond.png" alt="" />
							<div>欢迎登录</div>
							<img src="../../../global-assets//imgs/diamond.png" style="transform: rotateY(180deg)" />
						</div>
						<a-form-item name="userNumber" :rules="[{ required: true, message: '请输入账号' }]">
							<p class="item-title">账号</p>

							<a-input v-model:value.trim="C_UserNumber" size="large" :style="C_InputWH(1)" placeholder="请输入" :maxlength="11"></a-input>
						</a-form-item>
						<a-form-item name="password" :rules="[{ required: true, message: '请输入密码' }]">
							<p class="item-title">密码</p>
							<a-input-password
								v-model:value.trim="C_Password"
								:style="C_InputWH(1)"
								size="large"
								placeholder="请输入"
								:maxlength="20"
							></a-input-password>
						</a-form-item>
						<div class="verify-code-group">
							<a-form-item name="captcha" :rules="[{ required: true, message: '请输入验证码' }]">
								<p class="item-title">验证码</p>
								<a-input v-model:value.trim="C_ImgCode" size="large" :style="C_InputWH(2)" placeholder="请输入" :maxlength="5"></a-input>
							</a-form-item>
							<global-verify-code
								:img-src="imgCodeSrc"
								style="z-index: 333; margin-top: 48px; margin-left: 8px"
								@update-code="GetImgVerifyCode"
							></global-verify-code>
						</div>
					</a-form>
					<a-button class="login-btn" type="primary" size="large" :loading="loading" @keyup.enter="enterdown" @click="UserLogin"
						>登录</a-button
					>
				</div>
			</div>
		</div>
	</div>

	<div v-else class="login2">
		<a-spin size="large" tip="加载中..."></a-spin>
	</div>
</template>

<script setup lang="ts" name="login-page">
import { g6RandomId, g6FileOperate, g6Permission, g6RegValidate } from 'glasssix-utils-ts';

import Router from '@/global-router/index';
import { MenusAPI } from '@/global-services/api';
import { useG6Crypto } from '@/global-hooks/base.hooks';
import { TsLoginForm } from '../../type';
import { apiImgVerifyCode, apiUserLogin, apiUserLogin2 } from '../../api';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const loginForm = reactive<TsLoginForm>({ loginType: '' });
const prefixKey = ref(g6RandomId());
const imgCodeSrc = ref('');
const { cryptoObj, GetCryptoFun } = useG6Crypto();

const C_UserNumber = computed({
	get: () => loginForm.userNumber,
	set(val) {
		loginForm.userNumber = (val as string).replace(/\s*/g, '');
	}
});
const C_Password = computed({
	get: () => loginForm.password,
	set(val) {
		loginForm.password = (val as string).replace(/\s*/g, '');
	}
});
const C_ImgCode = computed({
	get: () => loginForm.captcha,
	set(val) {
		loginForm.captcha = (val as string).replace(/\s*/g, '');
	}
});

const C_InputWH = computed(() => {
	return (type: number) => {
		let obj = {
			width: type === 1 ? '360px' : '232px',
			height: ' 44px'
		};
		return obj;
	};
});

// 获取&更新图片验证码
const GetImgVerifyCode = (): void => {
	// eslint-disable-next-line promise/catch-or-return
	apiImgVerifyCode({ prefix: prefixKey.value }).then((res: TsRes) => {
		// eslint-disable-next-line promise/always-return
		if (res.code === 0) {
			imgCodeSrc.value = g6FileOperate.arrayBufferToBase64(res.data, 'png');
		}
	});
};

// 获取登录的菜单数据
const getRoleMenus = async () => {
	const layoutItems = Array.isArray(Router.options.routes) ? Router.options.routes.find((item) => item.name === 'layout') : [];
	const res: TsRes = await MenusAPI.roleMenus();
	if (res.code === 0 && Array.isArray(res.data)) {
		g6Permission.getRolePermissionData(res.data, layoutItems.children);
	}
};

//
const refForm = ref();
const UserLogin = (): void => {
	g6RegValidate.formSubmit(refForm.value, async () => {
		try {
			loginForm.loginType = '1';
			loading.value = true;
			let newForm = JSON.parse(JSON.stringify(loginForm));

			newForm.prefix = prefixKey.value;
			const cryptoData = cryptoObj.enCryptoFun(newForm);
			const res: any = await apiUserLogin(cryptoData);
			if (res.code === 0) {
				const userInfo: TsUser = {
					userName: res.data.userName,
					userNumber: res.data.userNumber,
					phone: res.data.phone,
					roleId: res.data?.roleId,
					userId: res.data.personId,
					color: res.data.color,
					backgroundColor: res.data.backgroundColor
				};
				sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
				sessionStorage.setItem('firstSkipRealVideo', '0'); //是否是登录后第一次跳转到监控中心
				sessionStorage.setItem('token', res.data.token);
				localStorage.setItem('inOrOutNetwork', res.data.inOrOutNetwork);
				// $message.success('成功');

				await getRoleMenus();

				router.push('/');
			} else {
				prefixKey.value = g6RandomId();
				loginForm.captcha = '';
				GetImgVerifyCode(); // 失败后刷新图形验证码
			}
		} finally {
			loading.value = false;
		}
	});
};
const enterdown = (e: any): void => {
	if (e.keyCode === 13) {
		UserLogin();
	}
};

const showLogin2 = ref(false);
const login2 = async (userNumber: string, pwd: string) => {
	await GetCryptoFun();

	nextTick(async () => {
		const cryptoData = cryptoObj.enCryptoFun({
			loginType: '1',
			userNumber: userNumber,
			password: pwd,
			prefix: prefixKey.value
		});
		const res: any = await apiUserLogin2(cryptoData);
		if (res.code === 0) {
			const userInfo: TsUser = {
				userName: res.data.userName,
				userNumber: res.data.userNumber,
				phone: res.data.phone,
				roleId: res.data?.roleId,
				userId: res.data.personId,
				color: res.data.color,
				backgroundColor: res.data.backgroundColor
			};
			sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
			sessionStorage.setItem('firstSkipRealVideo', '0'); //是否是登录后第一次跳转到监控中心
			sessionStorage.setItem('token', res.data.token);
			localStorage.setItem('inOrOutNetwork', res.data.inOrOutNetwork);
			// $message.success('成功');

			await getRoleMenus();

			router.push('/');
			showLogin2.value = false;
		} else {
			showLogin2.value = false;
			prefixKey.value = g6RandomId();
			loginForm.captcha = '';
			GetImgVerifyCode(); // 失败后刷新图形验证码
		}
	});
};

onMounted(async () => {
	window.addEventListener('keydown', enterdown);
	sessionStorage.clear();

	console.log('登录route', route);

	if (route.query.userName && route.query.pwd) {
		showLogin2.value = true;
		login2(route.query.userName as string, route.query.pwd as string);
	} else {
		showLogin2.value = false;
		loginForm.userNumber = '';
		loginForm.password = '';
		loginForm.prefix = '';
		loginForm.captcha = '';
		GetImgVerifyCode();
	}
});

onUnmounted(() => {
	window.removeEventListener('keydown', enterdown, false);
});
</script>

<style lang="less" scoped>
input:-internal-autofill-previewed,
input:-internal-autofill-selected {
	-webkit-text-fill-color: @text01;
	transition: background-color 50000s ease-out 0.5s;
}

.login2 {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100vh;
}

.login-page-container {
	// z-index: 11;
	width: 100%;
	height: 100%;
	background: #000;
	background-image: url('../../../global-assets/gif/start.gif');
	background-repeat: no-repeat;
	background-size: cover;

	.lottieMain {
		// z-index: 99;
	}

	.login-page {
		display: flex;
		// position: relative;
		overflow-x: auto;
		width: 100%;
		height: 100%;
		align-items: center;
		justify-content: center;

		.imgg {
			position: relative;
			z-index: 11;
			width: 100%;
			height: 100%;
		}

		.login-page-from {
			z-index: 999;
			display: flex;
			align-items: center;
		}

		.login-form-card {
			margin-bottom: 100px;

			.login-title {
				font-family: TENGXIANGZHIHEIJIAN;
				font-size: 40px;
				font-weight: 400;
				font-style: normal;
				line-height: normal;
				letter-spacing: 4px;
				background: linear-gradient(180deg, #bdc4cb 0%, #fff 100%);
				background-clip: text;
				-webkit-text-fill-color: transparent;
			}

			._title {
				display: flex;
				margin: 50px 0 12px;
				align-items: center;
				margin-left: 20px;

				div {
					margin: 0 30px;
					font-size: 24px;
					font-weight: 700;
					font-style: normal;
					line-height: 32px; /* 133.333% */
					color: @text01;
				}
			}

			.item-title {
				margin-top: 20px;
				margin-bottom: 8px;
				font-size: 16px;
				font-style: normal;
				line-height: 24px;
				color: @text02;
			}

			.ant-form {
				.ant-form-item {
					.ant-input,
					.ant-input-password {
						border: 1px solid @mask02;
						border-radius: 6px;
						background-color: transparent;
					}

					:deep(.ant-input-affix-wrapper .anticon.ant-input-password-icon) {
						color: #d5d5d5;
					}
				}
			}

			.verify-code-group {
				display: flex;
				align-items: center;
			}

			.login-btn {
				z-index: 999;
				width: 362px;
				height: 44px !important;
				margin-top: 46px;
				margin-left: 90px;
				border-radius: 6px !important;
				background: linear-gradient(180deg, #2d7cfc 0%, #185dcc 100%);
				box-shadow: 0 2px 0 0 rgba(0, 0, 0, 0.04);
				cursor: pointer;

				&:hover {
					z-index: 999;
					border-radius: 6px;
					background: linear-gradient(180deg, #4188fa 0%, #3070d6 100%);
					box-shadow: 0 2px 0 0 rgba(0, 0, 0, 0.04);
				}

				&:active {
					z-index: 999;
					border-radius: 6px;
					background: linear-gradient(180deg, #286fe1 0%, #1755bb 100%);
					box-shadow: 0 2px 0 0 rgba(0, 0, 0, 0.04);
				}
			}
		}
	}
}
</style>
